import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';
import { getUserList, editRecord, deleteRecord, addRecord } from './service';

const UserModel = {
  namespace: 'users',
  state: {
    data: [],
  },
  effects: {
    *getUsers(action, { call, put }) {
      const data = yield call(getUserList);
      if (data) {
        yield put({ type: 'save', payload: data });
      }
    },
    *edit({ payload: { id, values } }, { call, put }) {
      // console.log('edit here')
      // console.log(action.payload.id)
      console.log('edit-id:', id)
      const data = yield call(editRecord, id, values)
      yield put({
        type: 'getUsers',
      })
    },
    *delete({ payload: { id } }, { call, put }) {
      console.log('delete-id', id)
      const data = yield call(deleteRecord, id)
      yield put({
        type: 'getUsers',
      })
    },
    *add({ payload: { values } }, { call, put }) {
      yield call(addRecord, values)
      yield put({
        type: 'getUsers'
      })
    }
  },
  reducers: {
    save(state, action) {
      // console.log('reducer', action.payload.data)
      return action.payload;
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/') {
          dispatch({
            type: 'getUsers',
          });
        }
      });
    },
  },
};
export default UserModel;
